<template>
  <q-menu
    ref="menuRef"
    v-model="showMenu"
    :target="computedTarget"
    anchor="bottom left"
    self="top left"
    fit
    class="user-menu"
    :no-parent-event="true"
    max-height="400px"
    :separate-close-popup="false"
    @hide="handleHide"
    @show="handleShow"
    @before-show="handleBeforeShow"
  >
    <q-list style="min-width: 200px" class="user-menu-list">
      <!-- 用户信息头部 -->
      <q-item class="user-menu-header">
        <q-item-section avatar>
          <q-avatar 
            size="48px"
            :style="getAvatarStyle(currentUser?.open_id || currentUser?.id || currentUser?.name)"
          >
            <img v-if="avatarUrl" :src="avatarUrl" />
            <div v-else class="avatar-placeholder">
              {{ currentUser?.name?.[0]?.toUpperCase() || 'U' }}
            </div>
          </q-avatar>
        </q-item-section>
        <q-item-section>
          <q-item-label class="user-name">{{ currentUser?.name || '用户' }}</q-item-label>
          <q-item-label caption class="user-email">{{ currentUser?.email || '' }}</q-item-label>
        </q-item-section>
      </q-item>

      <q-separator />

      <!-- 个人资料 -->
      <q-item clickable v-close-popup @click="handleProfile">
        <q-item-section avatar>
          <q-icon name="person" />
        </q-item-section>
        <q-item-section>
          <q-item-label>个人资料</q-item-label>
        </q-item-section>
      </q-item>

      <q-separator />

      <!-- 帮助 -->
      <q-item clickable v-close-popup @click="handleHelp">
        <q-item-section avatar>
          <q-icon name="help" />
        </q-item-section>
        <q-item-section>
          <q-item-label>帮助与反馈</q-item-label>
        </q-item-section>
      </q-item>

      <q-separator />

      <!-- 退出登录 -->
      <q-item clickable @click="handleLogout" class="logout-item">
        <q-item-section avatar>
          <q-icon name="exit_to_app" />
        </q-item-section>
        <q-item-section>
          <q-item-label>退出登录</q-item-label>
        </q-item-section>
      </q-item>
    </q-list>
  </q-menu>
</template>

<script setup lang="ts">
import { computed, ref, watch, nextTick } from 'vue'
import type { QMenu } from 'quasar'
import type { User } from '../services/auth'
import { API_BASE_URL } from '@/config/env'
import { getAvatarStyle } from '@/utils/avatar'
import { getCachedImageUrl } from '@/services/image-cache'

const props = defineProps<{
  modelValue: boolean
  currentUser: User | null
  target?: HTMLElement | null
  targetSelector?: string
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'profile': []
  'help': []
  'logout': []
  'close': []
}>()

const menuRef = ref<QMenu | null>(null)
const avatarUrl = ref<string | null>(null)

// 计算 target，优先使用 targetSelector，然后是 target
const computedTarget = computed(() => {
  if (props.targetSelector) {
    return props.targetSelector
  }
  if (props.target) {
    return props.target
  }
  return undefined
})

const showMenu = computed({
  get: () => {
    return props.modelValue
  },
  set: (val) => {
    emit('update:modelValue', val)
  },
})

// 监听 modelValue 和 target 变化，确保菜单能正确显示
watch([() => props.modelValue, () => props.target, () => props.targetSelector], async ([newVal, newTarget, newSelector]) => {
  if (newVal) {
    await nextTick()
    const targetElement = newTarget || (newSelector ? document.querySelector(newSelector) : null)
    if (targetElement) {
      console.log('UserMenu: 准备显示菜单', { target: !!newTarget, selector: newSelector, element: targetElement })
    } else {
      console.warn('UserMenu: modelValue 为 true 但 target 不存在', { target: !!newTarget, selector: newSelector })
    }
  }
}, { immediate: true })

const handleBeforeShow = (evt: any) => {
  console.log('UserMenu: 菜单即将显示', { target: !!props.target, selector: props.targetSelector, event: evt })
  // 确保 target 存在
  const targetElement = props.target || (props.targetSelector ? document.querySelector(props.targetSelector) : null)
  if (!targetElement) {
    console.warn('UserMenu: target 不存在，阻止显示')
    evt.preventDefault?.()
  }
}

const handleShow = () => {
  console.log('UserMenu: 菜单已显示', { target: !!props.target, selector: props.targetSelector })
}

const handleHide = () => {
  console.log('UserMenu: 菜单已隐藏')
  // 当菜单隐藏时，同步更新 modelValue
  if (props.modelValue) {
    emit('update:modelValue', false)
  }
  emit('close')
}

// 加载头像（使用缓存服务）
const loadAvatar = async () => {
  if (props.currentUser?.file_name) {
    try {
      const url = `${API_BASE_URL}/api/upload/${props.currentUser.file_name}`
      const cachedUrl = await getCachedImageUrl(url)
      avatarUrl.value = cachedUrl
    } catch (error) {
      console.error('加载头像失败:', error)
      avatarUrl.value = null
    }
  } else {
    avatarUrl.value = null
  }
}

// 监听 currentUser 变化，重新加载头像
watch(() => props.currentUser?.file_name, () => {
  loadAvatar()
}, { immediate: true })

const handleProfile = () => {
  emit('profile')
}

const handleHelp = () => {
  emit('help')
}

const handleLogout = async () => {
  console.log('UserMenu: 退出登录被点击')
  // 先关闭菜单
  showMenu.value = false
  // 然后触发 logout 事件
  emit('logout')
}
</script>

<style lang="sass" scoped>
.user-menu
  border-radius: 12px
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12)
  z-index: 9999 !important
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif
  -webkit-font-smoothing: antialiased
  -moz-osx-font-smoothing: grayscale

.user-menu-list
  padding: 6px 0

  :deep(.q-item)
    min-height: 44px
    padding: 10px 16px
    transition: background-color 0.15s ease

    &:hover
      background-color: rgba(0, 0, 0, 0.04)

    .q-item__label
      font-size: 14px
      font-weight: 500
      letter-spacing: 0.01em
      line-height: 1.5
      color: #1a1a1a
      -webkit-font-smoothing: antialiased
      -moz-osx-font-smoothing: grayscale

    .q-icon
      font-size: 18px
      opacity: 0.7
      transition: opacity 0.15s ease

    &:hover .q-icon
      opacity: 1

.user-menu-header
  padding: 14px 16px
  background: #ffffff
  border-bottom: 1px solid rgba(226, 232, 240, 0.8)

  .user-name
    font-weight: 600
    font-size: 15px
    color: #000000
    letter-spacing: -0.01em
    line-height: 1.4
    -webkit-font-smoothing: antialiased
    -moz-osx-font-smoothing: grayscale

  .user-email
    font-size: 12px
    font-weight: 400
    color: #718096
    margin-top: 4px
    letter-spacing: 0.02em
    line-height: 1.5
    -webkit-font-smoothing: antialiased
    -moz-osx-font-smoothing: grayscale

.avatar-placeholder
  width: 100%
  height: 100%
  display: flex
  align-items: center
  justify-content: center
  color: white
  font-weight: 500
  font-size: 18px
  letter-spacing: 0
  border: 1px solid #E5E5E5
  -webkit-font-smoothing: antialiased
  -moz-osx-font-smoothing: grayscale

.logout-item
  color: #ef4444

  .q-item__label
    color: #ef4444

  &:hover
    background: rgba(239, 68, 68, 0.1)
</style>

